package com.cy.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.cy.common.RpcRequest;
import com.cy.common.RpcResponse;
import com.cy.rpc.consumer.client.RpcClient;
import com.cy.rpc.consumer.config.RpcServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
@Component
public class RpcClientProxy {

    @Autowired
    RpcServerConfig rpcServerConfig;

    private int currentIndex = 0;

    private List<SocketAddress> socketAddresses;

    public Object createProxy(Class serviceClass) {

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //先获取这次需要请求的地址
                        SocketAddress socketAddress = getSocketAddress();
                        System.out.println("当前访问你的是=="+socketAddress);
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.创建RpcClient对象
                        RpcClient rpcClient = new RpcClient(socketAddress);
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            rpcClient.close();
                        }

                    }
                });
    }

    /**
     * 获取socket地址
     * @return
     */
    private SocketAddress getSocketAddress() {
        //初始化
        if (socketAddresses == null){
            initAddList();
        }
        SocketAddress socketAddress = socketAddresses.get(currentIndex);
        //如果超出最大值，则重置为0
        currentIndex = currentIndex + 1 >= socketAddresses.size() ? 0 : currentIndex + 1;
        return socketAddress;
    }

    private void initAddList() {
        String addressStr = rpcServerConfig.getAddress();
        String[] addresses = addressStr.split(",");
        socketAddresses = new ArrayList<>();
        for (String address : addresses) {
            String[] addressAndPort = address.split(":");
            String add = addressAndPort[0];
            int port = Integer.parseInt(addressAndPort[1]);
            socketAddresses.add(new InetSocketAddress(add, port));
        }
    }
}
